package com.qili.controller;

import com.qili.base.entity.CurrentUser;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.sys.SysMenu;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.service.search.SearchIndexService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.util.CommonUtil;
import com.qili.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author liuyang
 * @date 2020/11/3
 * @description
 */
@RequestMapping("/search/index")
@Controller
public class SearchIndexController {

    @Autowired
    private SearchIndexService searchIndexService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SupervisorFileService supervisorFileService;

    /**
     * 智能检索系统首页
     * @param model
     * @param request
     * @return
     */
    @GetMapping("")
    @RequiresPermissions("zn:index")
    public String showIndex(Model model, HttpServletRequest request){

        //查询左侧三层目录结构
        List<SysMenu> menuList = searchIndexService.selectLeftMenus();
        model.addAttribute("left",menuList);
        //带出用户头像姓名
        CurrentUser currentUser = CommonUtil.getUser();
        String userId=CommonUtil.getUserId();
        SysUser sysUser=sysUserService.selectByPrimaryKey(userId);
        if(sysUser==null){
            // 跳转到登陆页面
            request.setAttribute("type","login");
            return "/login";
        }
        // 个人中心设置的数量
        String tagnum=sysUser.getNumTag();
        currentUser.setNumTag(tagnum);
        String AsTags = currentUser.getTags();
        String[] AyTags;
        if (StringUtil.isNotBlank(AsTags)  &&  StringUtil.isNotBlank(tagnum) ) {
            String[] newAyTags=new String[Integer.valueOf(tagnum)];
            AyTags = AsTags.split(";");
            int  length=AyTags.length;
            if(Integer.valueOf(tagnum)<length){
                //清除多余的0
                for (int i = 0; i < length; i++) {
                    if(i<Integer.valueOf(tagnum)){
                        newAyTags[i]=AyTags[i];
                    }
                }
                currentUser.setTags( StringUtils.join(newAyTags, ";") + ";");
            }
        }
        Session session = com.qili.core.shiro.Principal.getSession();
        session.setAttribute("currentPrincipal", currentUser);
        SupervisorFile supervisorFile =  supervisorFileService.getPersonalImg(userId);
        request.setAttribute("file", supervisorFile);
        return "searchIndex";
    }

}
